package com.lnsf.bookstore.common.shiro.realm;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.lnsf.bookstore.common.constant.Constants;
import com.lnsf.bookstore.common.session.SessionProvider;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.lnsf.bookstore.system.permission.vo.Permission;
import com.lnsf.bookstore.system.role.vo.Role;
import com.lnsf.bookstore.system.user.service.UserService;
import com.lnsf.bookstore.system.user.vo.User;

public class MyRealm extends AuthorizingRealm  {
	
	Logger logger = Logger.getLogger(MyRealm.class);	
	
	@Autowired
	private UserService userService;

	@Autowired
    private SessionProvider sessionProvider;


    @Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		//角色名的集合  
        Set<String> roles = new HashSet<String>();  
        //权限名的集合  
        Set<String> permissions = new HashSet<String>();
        
		String username=  (String) principal.getPrimaryPrincipal();
		//VipUser vipuser = userService.getByUserName(username);
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		Set<Role> roleSet =  userService.getUserByName_roleAndPer(username).getRoleSet();
        Iterator<Role> it = roleSet.iterator();
       
        while(it.hasNext()){
        	
        	Role role_1=it.next(); //set
        	roles.add(role_1.getName());  
        	//System.out.println("2"+it.next().getName());
            for(Permission per:role_1.getPermissionSet()){
                if (StringUtils.isBlank(per.getPerms()) ){
                    continue;
                }
                permissions.addAll(Arrays.asList(per.getPerms().trim().split(",")));
            }
        }
		simpleAuthorizationInfo.setRoles(roles);
		simpleAuthorizationInfo.setStringPermissions(permissions);
		
		return simpleAuthorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		String username= (String) token.getPrincipal();
	/*	String phone= (String) token.getPrincipal();*/
		//System.out.println(username);
        User user = userService.getByUserName(username);
		/*VipUser vipuser = userService.getByPhone(phone);*/
        sessionProvider.setUser(user);
        //SecurityUtils.getSubject().getSession().setAttribute(Constants.ADMIN_SESSION_KEY,user);
        if(user == null) {  
            throw new UnknownAccountException();//没找到帐号  
        } 
        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以在此判断或自定义实现  
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(  
                user.getUsername(), //用户名  
                user.getPassword(), //密码  
                ByteSource.Util.bytes(user.getSalt()), 
                getName()  //realm name  
        );  
        
        
       System.out.println(user.getSalt());
        return authenticationInfo;  
    }  
	
	
	
}
